package com.dgut.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dgut.common.model.entity.Contract;
import com.dgut.common.model.entity.ContractGoods;
import com.dgut.common.model.entity.Goods;
import com.dgut.common.service.ContractGoodsService;
import com.dgut.common.service.ContractService;
import com.dgut.common.service.GoodService;
import com.dgut.common.util.SystemJsonResponse;
import com.dgut.service.ContractsService;

/**
 * @author huangyujia <huangyujia@kuaishou.com>
 * Created on 2024-06-18
 */
@Service
public class ContractsServiceImpl implements ContractsService {

    @Autowired
    private ContractService contractService;

    @Autowired
    private GoodService goodService;

    @Autowired
    private ContractGoodsService contractGoodsService;

    @Override
    public SystemJsonResponse createContract(Map<String, Integer> goodsMap) {
        Set<String> goodIds = goodsMap.keySet();
        List<Goods> goodList = goodService.getByIds(goodIds);
        Map<String, Goods> idToGoods = goodList.stream().collect(Collectors.toMap(Goods::getId, good -> good));
        for (String goodId : goodIds) {
            if(idToGoods.get(goodId).getCount() < goodsMap.get(goodId)) {
                return SystemJsonResponse.fail("库存不足");
            }
        }
        Contract contract = new Contract();
        contract.setStatus(0);
        contractService.save(contract);
        List<ContractGoods> contractGoodsList = new ArrayList<>();
        for (String goodId : goodIds) {
            Goods goods = idToGoods.get(goodId);
            goods.setCount(goods.getCount() - goodsMap.get(goodId));
            ContractGoods contractGoods = new ContractGoods();
            contractGoods.setContractId(contract.getId());
            contractGoods.setGoodsId(goodId);
            contractGoodsList.add(contractGoods);
        }
        contractGoodsService.saveBatch(contractGoodsList);
        Collection<Goods> goods = idToGoods.values();
        for (Goods good : goods) {
            goodService.updateById(good);
        }
        return SystemJsonResponse.success();
    }

    @Override
    public SystemJsonResponse finishContract(Contract contract) {
        contractService.updateById(contract);
        return SystemJsonResponse.success();
    }
}
